# coding=utf-8
import docx
import re
import os
from openpyxl import load_workbook
from utils.file import get_file_list
from utils.excel import BaseExcel

def read_word(folder, title, key=None, reverse=None, callback=None):
    """
    快速读取word中表格数据，返回excel数据对象
    :param folder: 存放word的文件夹
    :param title: 需要读取的内容项(即excel的标题)
    :param key: 排序项。可填【文件名称、修改日期、文件大小】
    :param reverse: 排序方式。可填【升序、降序】，升序代表从小到大晚往上升，降序代表从大到小往下降
    :param callback: 回调函数，可以获取到读取过程，参数为当前读取位置、word总数和当前读取的word文件
    :return:
    """
    e = BaseExcel()  # 创建excel数据对象
    e.title = title
    word_list = get_file_list(folder, ".docx", key, reverse)  # 按照顺序获取word列表
    for word_index, word_name in enumerate(word_list):
        word_file = docx.Document(os.path.join(folder,word_name))
        if len(word_file.tables) == 0:  # 没有发现表格
            continue
        table = word_file.tables[0]
        table_dict = {key: None for key in e.title}  # 数组存储
        for row in table.rows:  # 遍历所有的行列
            for col, cell in enumerate(row.cells):
                if cell is None or len(cell.text) == 0:  # 如果为空就跳过
                    continue
                cell_text = re.sub(r"\s", "", str(cell.text))  # 去除空格、换行
                if cell_text in table_dict:
                    table_dict[cell_text] = row.cells[col + 1].text  # 读取当前title后的结果
        table_list = [table_dict[key] for key in e.title]  # dict转换为list
        e.append(table_list)  # 添加数据
        print("In Progress:  读取%s成功" % word_name)
        if callback is not None:
            callback(word_index, len(word_list), word_name)
    return e


def read_excel(folder, title, key=None, reverse=None, callback=None):
    """
    快速读取excel中表格数据，返回excel数据对象
    :param folder:参数同上
    :param title:
    :param key:
    :param reverse:
    :param callback:
    :return:
    """
    e = BaseExcel()  # 创建excel数据对象
    e.title = title
    excel_list = get_file_list(folder, ".xlsx", key, reverse)  # 按照顺序获取word列表
    for excel_index, excel_name in enumerate(excel_list):
        wb = load_workbook(os.path.join(folder,excel_name))
        ws = wb.active
        table_dict = {key: None for key in e.title}  # 数组存储
        for row in ws.values:  # 遍历所有的行列
            for col, cell in enumerate(row):
                if cell is None or len(str(cell)) == 0:  # 如果为空就跳过
                    continue
                cell_text = re.sub(r"\s", "", str(cell))  # 去除空格、换行
                if cell_text in table_dict:
                    table_dict[cell_text] = row[col + 1]  # 读取当前title后的结果
        table_list = [table_dict[key] for key in e.title]  # dict转换为list
        e.append(table_list)  # 添加数据
        print("In Progress:  读取%s成功" % excel_name)
        if callback is not None:
            callback(excel_index, len(excel_list), excel_name)
    return e